package com.javabi.unix.line;

import static java.lang.ClassLoader.getSystemClassLoader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ResourceLineReader {

	private final String resource;

	public ResourceLineReader(String resource) {
		if (resource.isEmpty()) {
			throw new IllegalArgumentException("resource is empty");
		}
		this.resource = resource;
	}

	public <R> R readLines(ILineProcessor<R> processor) throws IOException {
		InputStream input = getSystemClassLoader().getResourceAsStream(resource);
		if (input == null) {
			throw new IllegalStateException("resource not found: '" + resource + "'");
		}
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
			while (true) {
				String line = reader.readLine();
				if (line == null) {
					break;
				}
				processor.processLine(line);
			}
			return processor.getResult();
		} finally {
			input.close();
		}
	}

}
